//每天的时间点
var hours = new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24);
//当前日期对象
var currentDate = new Date();
//页面加载完后响应onReady事件
$(function(){	
	
	//页面初始化时获取报表名称
	var reportName = $('#reportname').val();
	
	//reportname绑定change事件
	$('#reportname').bind('change',function(){
		if ($(this).validatebox("isValid"))
		{
			$.ajax({
				url:ctx+'/urgentrptmgr/speedReportAction!checkNameIsValid.action',
				data:{reportName:$('#reportname').val()},
				dataType:'json',
				success:function(data){
					if(data=='1'){
						window.top.$.messager.alert('提示', '该指标名称已经存在，请检查！');
						$('#reportname').val(reportName).focus();
					}
				}
			});
		}
	});
	//初始化周期类型
	$('#periodtype').combobox({
		url:ctx+'/basemgr/kqiManagerAction!getDic.action?dictType=periodType&tableName=TD_KQI_DEFINE&excludeValues=1,4',  
		valueField:'codeValue',
		textField:'codeName',
 	 	editable:false,
 		required:true,
 		onLoadSuccess:function(){
 			//针对int类型默认值为0的处理
 			if ($(this).combobox('getValue') == 0)
 			{
 				$(this).combobox("setValue", "");
 			}
 		},
		onSelect:function(){
			//当周期类型发生变化时，判断是否已经配置过规则,
			//如果已配置过规则并且当前的周期类型不等于周期类型的隐藏标识的值时给出提示
			if ($("#periodTypeFlag").val() != ''
				&& $(this).combobox('getValue') != $("#periodTypeFlag").val())
			{
				//从页面获取配置规则的条数
				if($(".history-date ul li.green").size() > 0){
					window.top.$.messager.alert('提示', '该周期类型已配置了检查规则,如需修改请先删除所有的配置规则!');
					$(this).combobox('setValue', $("#periodTypeFlag").val());
					return false;
	 	 	    }
			}
			loadCheckTime($(this).combobox('getValue'));
			loadCheckRule($(this).combobox('getValue'));
		}
	});
	$('#requiresrc').combobox({
		url:ctx+'/basemgr/kqiManagerAction!getDic.action?dictType=requireSrc&tableName=TD_SPEED_REPORT_DEFINE&&excludeValues=4',  
		valueField:'codeValue',
		textField:'codeName',
 	 	editable:false,
 	 	required:true,
 	 	onLoadSuccess:function(){
			//不让第一条为默认选择项
			$('#requiresrc').combobox('unselect',0);
		}
	});	
	
	loadCheckTime($("#periodtype").val());
	loadCheckRule($("#periodtype").val());
	spreadSpeedInfo();
	getAllCheckPointConfig();
});	

/**
 * 加载检查时间点的数据,如果periodType为空,默认加载周期类型为天的数据
 * @param periodType 3:日   2:月
 */
function loadCheckTime(periodType){
	
	$("#check_point_time_td").empty().html("<input id=\"check_point_time\" name=\"checktime\" data-options=\"required:true,missingMessage:'请选择检查时间点'\"  style=\"width:180px;\"/>");
	//时间点数组
	var dataArray = new Array();
	if(periodType == '3'){
		for(var i=0; i<hours.length; i++){
			dataArray[i] = {label:hours[i]+"时", value:hours[i]};
		}
	}
	else if(periodType == '2'){
		//获取本月天数
		var days = new Date(currentDate.getFullYear(), currentDate.getMonth()+1, 0).getDate();
		for(var i=0; i<days; i++){
			dataArray[i] = {label:(i+1)+"号", value:(i+1)};
		}
	}
	$('#check_point_time').combobox({
		textField:'label',
		valueField:'value',
		data:dataArray,
 	 	editable:false,
 	 	required:true
	});
	//检查时间点数据的input右侧增加日历图片
	$("#check_point_time").parent().find("span.combo-arrow").addClass("combo-arrow-checktime");
	$("#check_point_time").parent().find("span.combo-arrow")
		.mouseover(function(){
			$(this).removeClass("combo-arrow-checktime").addClass("combo-arrow-checktime-hover");
		})
		.mouseout(function(){
			$(this).removeClass("combo-arrow-checktime-hover").addClass("combo-arrow-checktime");
		});
}

/**
 * 加载检查点规则数据
 * @param queryPeriodType 3:日   2:月
 */
function loadCheckRule(queryPeriodType)
{
	
	$("#check_point_rule_td").empty().html('<input type="text" id="check_point_rule" name="rule"  data-options="required:true,missingMessage:\'请选择检查规则\'" style="width:180px;"/>');
	$("#tb").css("display", "none");
	//周期类型为月,查询日粒度的规则信息
	//周期类型为日,查询小时粒度的规则信息
	var periodType = "";
	if (queryPeriodType == "")
	{
		periodType = -1;
	}
	else
	{
		periodType = parseInt(queryPeriodType)+1;
	}
	
	$("#tb").css("display", "none");
	$('#check_point_rule').combogrid({  
        panelWidth:450,  
        idField:'ruleId', //ID字段  
        textField:'ruleName', //显示的字段  
        url:ctx+"/urgentrptmgr/speedReportAction!getCheckPointRule.action",  
        queryParams:{queryPeriodType:periodType},
        editable:false,
        fitColumns: true,  
        striped: true,  
        pagination : true,//是否分页  
        rownumbers:true,//序号  
        collapsible:false,//是否可折叠的  
        fit: true,//自动大小  
        pageSize: 10,//每页显示的记录条数，默认为10  
        pageList:[10,20,30],//可以设置每页记录条数的列表  
        method:'post',  
        columns:[[{field:'ruleId',hidden:true},
				  {field:'ruleName',title:'规则名称',width:150,align:'center'},				  
				  {field:'ruleType',title:'规则类型',width:50,align:'center',hidden:true},
				  {field:'ruleAlgorithmName',title:'规则算法',width:140,align:'center'},
				  {field:'ruleVersionNum',title:'版本号',width:50,align:'center',hidden:true},
				  {field:'warnLevelName',title:'告警级别',width:150,align:'center'},
				  {field:'thresholdMax',title:'阀值上限',width:80,align:'center'},
				  {field:'thresholdMin',title:'阀值下限',width:80,align:'center'}				 				 
				]],
		toolbar:'#tb'
    }); 
}

/**
 * 获取报表下所有已配置的规则信息
 */
function getAllCheckPointConfig(){
	$.ajax({
		url:ctx+'/urgentrptmgr/speedReportAction!getRuleByReportId.action',
		data:{reportId:$('#reportid').val(),reportType:$("#reporttype").val()},
		dataType:'json',
		success:function(data){						
			createGZInfo(data);//构造时间轴				
		}
	});
}

/**
 * 显示急报快报概要信息
 */
function showSummary(){
	$('#tempReportname').html($('#reportname').val());
	$('#tempReporttype').html($('#reportTypeName').val());
	$('#tempPeriodtype').html($('#periodtype').combobox('getText'));
	$('#tempRequiresrc').html($('#requiresrc').combobox('getText'));
}

/**
 * 点击【修改】触发事件
 */
function spreadSpeedModInfo()
{
	spreadSpeedReportInfo();
	//输入框可用
	$("#reportname").attr("readonly", false);
	$("#requireResourceId").attr("readonly", false);
	$("#requireResourceName").attr("readonly", false);
	$("#requiredesc").attr("readonly", false);
	$("#requiresrc").combobox("enable");
	$("#periodtype").combobox("enable");
	
	$("#save_btn_div").css("display", "block");
	//移除【保存】的onclick事件
	$("#saveButton").unbind("click");
	//【保存】绑定修改报表信息的js
	$("#saveButton").bind("click", updateReport);
}

/**
 * 修改急报快报信息
 */
function updateReport()
{		
	$('#main_form').form('submit',{
		url:ctx+'/urgentrptmgr/speedReportAction!editSpeedReport.action',
		onSubmit:function(){
			if ($(this).form("validate"))
			{
				$("#saveButton").attr('disabled', true);
			}
			else
			{
				return false;
			}
		},
		success:function(result){
			$("#saveButton").attr('disabled', false);
			try{
				showSummary();
				//显示提示信息
				window.top.$.messager.show({title:'提示',msg:'修改急报快报基本信息成功！'});	
				//周期类型的隐藏标识
				$("#periodTypeFlag").val($("#periodtype").combobox('getValue'));
				spreadSpeedInfo();
				getAllCheckPointConfig();
				//刷新主列表
				window.top.$('#table_datagrid').datagrid('reload');																
			}catch(e){
				window.top.$.messager.alert('提示', e);
			}
		}
	});
}

//收缩按钮事件
function spreadSpeedInfo()
{
	var offset = $("#mainDiv").offset();
	$("#addDiv").slideUp("slow"); //关闭添加急报快报文本框
	$("#speedreportInfoDiv").slideDown("slow"); //展开急报快报信息
	$("#save_btn_div").css("display", "none");
	$("#spread_btn_div").css("display", "none");
	$("#pzgz_img_div").css({'top':offset.top+60, "left":offset.left});
	$("#showGZDiv").css("height", "480px");
	//隐藏配置规则div
	if($("#addPZDZ_div").css("display")=="block")
	{
		$("#addPZDZ_div").animate({left: "-20px", top:"-20px"},800,function(){$("#addPZDZ_div").css("display", "none");});
	}
}

//展开按钮事件
function spreadSpeedReportInfo()
{
	//输入框不可用
	$("#reportname").attr("readonly", true);
	$("#requireResourceId").attr("readonly", true);
	$("#requireResourceName").attr("readonly", true);
	$("#requiredesc").attr("readonly", true);
	$("#requiresrc").combobox("disable");
	$("#periodtype").combobox("disable");
	var offset = $("#mainDiv").offset();
	$("#addDiv").slideDown("slow"); //关闭添加急报快报文本框
	$("#speedreportInfoDiv").slideUp("slow"); 
	$("#save_btn_div").css("display", "none");
	$("#spread_btn_div").css("display", "block");
	$("#pzgz_img_div").css({'top':offset.top+240, "left":offset.left});
	$("#showGZDiv").css("height", "303px");
	//隐藏配置规则div
	if($("#addPZDZ_div").css("display")=="block")
	{
		$("#addPZDZ_div").animate({left: "-20px", top:"-20px"},800,function(){$("#addPZDZ_div").css("display", "none");});
	}
}

/**
 * 点击【配置规则】触发js
 */
function spreadAddGZ()
{
	if($("#addPZDZ_div").css("display")=="block")
	{
		$("#addPZDZ_div").animate({left: "-20px", top:"-20px"},800,function(){$("#addPZDZ_div").css("display", "none");});
	}
	else
	{
		var p = $("#pzgz_img_div").position();
		$("#addPZDZ_div").animate({left: p.left, top:p.top-10},800);
		$("#addPZDZ_div").css("display", "block");
		
	}	
	$('#check_point_time').combobox('clear');
	$('#check_point_rule').combogrid('clear');
	resetQuery();
	queryRule();
}

/**
 * 保存检查规则点配置信息
 */
function saveCheckPoint()
{
	var reportId=$('#reportid').val();//急报快报主键
	var timePoint=$('#check_point_time').combobox('getValue');//获得检查时间点	
	if(typeof timePoint == undefined || timePoint == null
			|| timePoint == '')
	{
		window.top.$.messager.alert('提示','检查时间点不能为空，请选择');
		return;
	}
	
	var ruleId=$('#check_point_rule').combogrid('getValue');//获得检查检查规则ID
	if(typeof ruleId == undefined || ruleId == null
			|| ruleId == '')
	{
		window.top.$.messager.alert('提示','检查规则不能为空，请选择');
		return;
	}	
	
	var versionNum='';		
    var g=$('#check_point_rule').combogrid('grid');
    var r=g.datagrid('getSelected');	// get the selected row
    versionNum=r.ruleVersionNum;   
    
    $.ajax({
		url:ctx+'/urgentrptmgr/speedReportAction!isCheckPointConfig.action',//校验在该 时间点是否已配置检查规则
		data:{reportId:reportId,timePoint:timePoint,ruleId:ruleId,reportType:$("#reporttype").val()},
		dataType:'json',
		beforeSend:function(){
			$("#saveGzButton").attr('disabled', true);
		},
		error:function(e){
			window.top.$.messager.alert('提示', e);
			$("#saveGzButton").attr('disabled', false);
		},
		success:function(data){
			if(data.returnFlag==true){				
				$.ajax({
					url:ctx+'/urgentrptmgr/speedReportAction!saveCheckPointConfig.action',
					data:{reportId:reportId,timePoint:timePoint,ruleId:ruleId,versionNum:versionNum
							,reportType:$("#reporttype").val()},
					dataType:'json',
					error:function(e){
						$("#saveGzButton").attr('disabled', false);
					},
					success:function(data){
						$.messager.show({title:'提示',msg:'检查点配置成功'});
						spreadAddGZ();	//收起配置窗口			
						createGZInfo(data);//构造时间轴		
						$("#saveGzButton").attr('disabled', false);
					}
				});												
			}else if(data.returnFlag==false){
				$.messager.alert('提示',data.returnMsg);
				$("#saveGzButton").attr('disabled', false);
				$('#check_point_time').combobox('clear');
				$('#check_point_rule').combogrid('clear');
				resetQuery();
				queryRule();
			}			
		}
	});           	
}

//st:对象  type:class名称  change:改变小图标的名称
function cbart (st,type,change) 
{ 
	document.getElementById(st).className = type;
	if(change!=""&&change!=null&&change!=undefined)
	{
		$("#"+st).children().children().attr("src",ctx+"/images/speedreport/"+change);
	}
} 
function sbart (st,type,change)
{ 
	document.getElementById(st).className = type;
	if(change!=""&&change!=null&&change!=undefined)
	{
		$("#"+st).children().children().attr("src",ctx+"/images/speedreport/"+change);
	}
}

//删除检查点规则配置信息并刷新时间轴
function deleCheckPointConfig(reportId,ruleId)
{
	var reportId=$('#reportid').val();//急报快报主键
	window.top.$.messager.confirm('提示','是否确定删除该检查点规则？',function(b){
		if(b){
			$.ajax({
				url:ctx+'/urgentrptmgr/speedReportAction!deleCheckPointConfig.action',
				data:{reportId:reportId,ruleId:ruleId,reportType:$("#reporttype").val()},
				dataType:'json',
				success:function(data){						
					createGZInfo(data);//构造时间轴				
				}
			});
		}
	});
}
//规则信息
function createGZInfo(data)
{
	var allLifeInfoHTML="";
	
	allLifeInfoHTML +='<div class="head-warp" style="padding-top:10px;*border-bottom:1px dashed #40A5D7;height:0px">   ';                                          
	allLifeInfoHTML +='  <div class="head">       ';                                                                                                               
	allLifeInfoHTML +='        <div class="nav-box" >     ';                                                                                                       
	allLifeInfoHTML +='          <ul>     ';                                                                                                                       
	allLifeInfoHTML +='              <li class="cur" style="text-align:left;padding-top:7px;padding-left:17px;font-size:30px;" ></li>';
	allLifeInfoHTML +='          </ul>     ';                                                                                                                      
	allLifeInfoHTML +='        </div>     ';                                                                                                                       
	allLifeInfoHTML +='  </div>      ';                                                                                                                            
	allLifeInfoHTML +='</div>      ';      
	allLifeInfoHTML +=' <div class="main" style="padding-left:12px;padding-top:20px">';
	allLifeInfoHTML +='  <div class="history" id="history">';
	allLifeInfoHTML +=' <div class="history-date">';
	allLifeInfoHTML +='  <ul>';
	allLifeInfoHTML +='	<div class="first"><a href="#nogo"></a></div>';
	allLifeInfoHTML +="	  </br>"; 
	allLifeInfoHTML +="	  </br>"; 
	allLifeInfoHTML +="	  </br>"; 
	allLifeInfoHTML +="	  </br>"; 
	allLifeInfoHTML +="	  </br>"; 
	
	if(data != null)
	{
		for(var i=0;i<data.length;i++)
		{
			allLifeInfoHTML +='<li class="green">';
			allLifeInfoHTML +='<h3><span>'+data[i].checkTime+getCheckTimeUnit()+'</span></h3>';
			allLifeInfoHTML +='<dl>';
			allLifeInfoHTML +='<dt>';
			
			allLifeInfoHTML +='<table class="showGZ" border="0">';
			allLifeInfoHTML +='<tr>';
			allLifeInfoHTML +='<td width="65px" height="44px">';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='<td align="left"><span class="showGZ-text1" style="color: #4f8fc7;font-size: 14px;" title="'+data[i].chekcRuleName+'">'+data[i].chekcRuleName+'</span>';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='<td align="right"><span class="pz_del_span"><img src="'+ctx+'/images/speedreport/gz_del_un.png" title="删 除" alt="删 除" onclick="deleCheckPointConfig(\''+data[i].reportId+'\', \''+data[i].ruleId+'\')">&nbsp;</span>';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='</tr>';
			
			allLifeInfoHTML +='<tr>';
			allLifeInfoHTML +='<td>';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='<td align="left">规则算法：'+data[i].ruleAlgorithmName;
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='<td align="left">告警级别：';
			allLifeInfoHTML +='<em class="'+warnLevelColor(data[i].warnLevel)+'" >'+data[i].warnLevelName+'</em>';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='</tr>';
			
			allLifeInfoHTML +='<tr>';
			allLifeInfoHTML +='<td>';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='<td colspan="2" align="left">阀值上限：'+data[i].thresholdMax;
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='</tr>';
			
			allLifeInfoHTML +='<tr>';
			allLifeInfoHTML +='<td>';
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='<td colspan="2" align="left">阀值下限：'+data[i].thresholdMin;
			allLifeInfoHTML +='</td>';
			allLifeInfoHTML +='</tr>';
			
			allLifeInfoHTML +='</table>';
			allLifeInfoHTML +='</dt>';
			allLifeInfoHTML +='</dl>';
			allLifeInfoHTML +='</li>';
	   
		}
	}
	
	allLifeInfoHTML +="	  </ul>"; 
	allLifeInfoHTML +="	  </br>"; 
	allLifeInfoHTML +="	  </br>"; 
	allLifeInfoHTML +="	  </div>"; 
	allLifeInfoHTML +="	  </div>"; 
	allLifeInfoHTML +="	  </div>"; 
	$("#showGZDiv").html(allLifeInfoHTML);
	$("#showGZDiv").css("display", "block");
}



//根据查询条件查询过滤规则
function queryRule()
{
	var ruleName=$('#query_ruleName').val();	
	var queryPeriodType = $("#periodtype").combobox('getValue');
	var periodType = "";
	if (queryPeriodType == "")
	{
		periodType = -1;
	}
	else
	{
		periodType = parseInt(queryPeriodType)+1;
	}
	var query={ruleName:ruleName,queryPeriodType:periodType}; //把查询条件拼接成JSON
	var grid=$("#check_point_rule").combogrid('grid');
	$(grid).datagrid('options').queryParams=query; //把查询条件赋值给datagrid内部变量
	$(grid).datagrid('load');
}
//重置查询条件
function resetQuery(){
	$('#query_ruleName').val('');
}

/**
 * 根据告警级别，告警内容显示相应的颜色
 * @param warnLevel
 */
function warnLevelColor(warnLevel)
{
	var className = "";
	
	//严重告警
	if (warnLevel == 3)
	{
		className = "warn_serious";
	}
	
	//重要告警
	else if (warnLevel == 2)
	{
		className = "warn_important";
	}
	
	//一般告警
	else if (warnLevel == 1)
	{
		className = "warn_common";
	}
	
	//正常
	else
	{
		className = "warn_normal";
	}
	
	return className;
}

/**
 * 根据周期类型获取时间点的单位信息
 * 月：单位是日
 * 日：单位是点
 */
function getCheckTimeUnit()
{
	var periodType = $("#periodTypeFlag").val();
	var unitName = "";
	//周期类型为月
	if(periodType == '2'){
		unitName = "日";
	}
	
	else if(periodType == '3'){
		unitName = "点";
	}
	
	return unitName;
}